package com.hqyj.javaSpringBoot.modules.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.javaSpringBoot.modules.account.dao.RoleDao;
import com.hqyj.javaSpringBoot.modules.account.dao.RoleResourceDao;
import com.hqyj.javaSpringBoot.modules.account.dao.UserRoleDao;
import com.hqyj.javaSpringBoot.modules.account.entity.Role;
import com.hqyj.javaSpringBoot.modules.account.service.RoleService;
import com.hqyj.javaSpringBoot.modules.common.entiy.ResultEntity;
import com.hqyj.javaSpringBoot.modules.common.entiy.SearchBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleResourceDao roleResourceDao;

    @Override
    @Transactional
    public ResultEntity<Role> insertRole(Role role) {
        List<Role> roles = Optional.ofNullable(roleDao.getRoleByRoleName(
                role.getRoleName())).orElse(Collections.emptyList());
        if (roles.isEmpty()){
            role.setCreateDate(LocalDateTime.now());
            roleDao.insertRole(role);
        }
        return new ResultEntity<Role>(
                ResultEntity.ResultStatus.SUCCESS.code,"insert success",role);
    }

    @Override
    @Transactional
    public ResultEntity<Role> deleteRole(int id) {
        roleDao.deleteRole(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        userRoleDao.deleteUserRoleByRoleId(id);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,"delete success");
    }

    @Override
    @Transactional
    public ResultEntity<Role> updateRole(Role role) {
        roleDao.updateRole(role);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,"update success");
    }

    @Override
    public Role getRoleByRoleId(int id) {
        return roleDao.getRoleByRoleId(id);
    }

    @Override
    public PageInfo<Role> getRoleBySearch(SearchBean searchBean) {
        searchBean.initSerchBean();
        PageHelper.startPage(searchBean.getCurrentPage(),searchBean.getPageSize());
        return new PageInfo<Role>(Optional.ofNullable(
                roleDao.getRoleBySearch(searchBean)).orElse(Collections.emptyList()));
    }

    @Override
    public List<Role> getRoles() {
        return roleDao.getRoles();
    }

    @Override
    public List<Role> getRolesByUserId(int userId) {
        return roleDao.getRolesByUserId(userId);
    }

    @Override
    public List<Role> getRolesByResourceId(int resourceId) {
        return roleDao.getRolesByResourceId(resourceId);
    }
}
